package com.sskj.fca.ui.fragment;


import android.annotation.SuppressLint;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sskj.boom.bean.EscapeBean;
import com.sskj.boom.widget.BoomView;
import com.sskj.common.SocketBean;
import com.sskj.common.adapter.MyFragmentPagerAdapter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerHorizenLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.TipMineUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.bean.UserBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.fca.R;
import com.sskj.fca.bean.CommonBean;
import com.sskj.fca.bean.MainMenuBean;
import com.sskj.fca.bean.OpenAwardBean;
import com.sskj.fca.bean.StockBloomBean;
import com.sskj.fca.bean.rxbus.LogoutBean;
import com.sskj.fca.bean.rxbus.MainChangeTabBean;
import com.sskj.fca.component.DaggerUserDataComponent;
import com.sskj.fca.presenter.QiangjinFragmentPresenter;
import com.sskj.fca.ui.adapter.QiangjinSpinnerAdapter;
import com.sskj.fca.ui.falling.FallObject;
import com.sskj.fca.ui.falling.FallingView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;

@Route(path = RConfig.APP_FRAGMENT_QIANGJIN)//FCA
public class QiangjinFragment extends BaseFragment<QiangjinFragmentPresenter> {
    @BindView(R.id.commonTabLayout)
    CommonTabLayout commonTabLayout;
    @BindView(R.id.ivBeBanker)
    ImageView ivBeBanker;
    @BindView(R.id.slidingTabLayout)
    SlidingTabLayout slidingTabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.boomView)
    BoomView boomView;
    @BindView(R.id.recyclerViewHistory)
    RecyclerView recyclerViewHistory;
    @BindView(R.id.rl_asset_record)
    RelativeLayout rlAssetRecord;
    @BindView(R.id.rl_banker_jackpot)
    RelativeLayout rlBankerJackpot;
    @BindView(R.id.btn_bet)
    Button btnBet;
    @Inject
    UserViewModel userViewModel;
    @BindView(R.id.et_bet)
    EditText etBet;
    @BindView(R.id.et_run_away)
    EditText etRunAway;
    @BindView(R.id.tv_max)
    TextView tvMax;
    @BindView(R.id.tv_award_poll)
    TextView tvAwardPoll;
    @BindView(R.id.tv_min)
    TextView tvMin;
    @BindView(R.id.tv_divide)
    TextView tvDivide;
    @BindView(R.id.tv_multiply)
    TextView tvMultiply;
    @BindView(R.id.tv_earn)
    TextView tvEarn;
    @BindView(R.id.tv_chance)
    TextView tvChance;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.tv_user_agreement)
    TextView tvUserAgreement;
    @BindView(R.id.tv_privacy_agreement)
    TextView tvPrivacyAgreement;
    @BindView(R.id.tv_help_center)
    TextView tvHelpCenter;
    @BindView(R.id.tv_now_value)
    TextView tv_now_value;
    @BindView(R.id.tv_app_download)
    TextView tvAppDownload;
    @BindView(R.id.tv_show_run)
    TextView tv_show_run;
    @BindView(R.id.iv_money_type)
    ImageView iv_money_type;
    @BindView(R.id.iv_boom)
    ImageView iv_boom;
    @BindView(R.id.iv_boom_handred)
    ImageView iv_boom_handred;
    @BindView(R.id.tv_clear_wanfa)
    ImageView tv_clear_wanfa;
    @BindView(R.id.ivBg)
    ImageView ivBg;
    @BindView(R.id.ll_wanfa_anim)
    LinearLayout ll_wanfa_anim;
    //    @Nullable
//    @BindView(R.id.surfaceFallView)
//    SurfaceFallView mSurfaceFallView;
    @BindView(R.id.fallingView)
    FallingView fallingView;
    private UserData userData;
    private SlimAdapter slimAdapter;

    private String userid = "";

    private int money_type = 0;
    private String betMax = "";
    private String betMin = "";
    private String betBeishu = "2";
    private String usdtBetMax = "";
    private String usdtBetMin = "";
    private String usdtBetBeishu = "2";
    private MaterialDialog loginTip;
    private List<EscapeBean> escapeBeans;
    private List<String> myMoney;
    private FallObject allObject;
    private AnimationDrawable boomAnimationDrawable;
    private AnimationDrawable handredAnima;

    private ArrayList<MainMenuBean> mainMenuBeans = new ArrayList<>();
    private QiangjinSpinnerAdapter spinnerAdapter;

    private String betType;

    //金币是否洒落
    private boolean isFall;
    //是否下注
    private boolean isBet;
    //是否逃跑
    private boolean isRun;
    //是否爆炸
    private boolean isBoom;
    //是否预约
    private boolean isSubscribe;
    //下注金额
    private double betMoney;
    //预约下注是否已请求
    private boolean isSubscriCommit;
    //预约下注金额
    private String subscribeBetMoney;
    //预约逃跑倍数
    private String subscribeBetValue;
    //预约下注币种
    private int subscribeBetType;
    //默认逃跑倍数
    private float betValue;
    private FallObject fallObject;

    @Override
    protected int getLayoutId() {
        return R.layout.app_fragment_qiangjin;
    }

    @Override
    public QiangjinFragmentPresenter getPresenter() {
        return new QiangjinFragmentPresenter();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeFive(StockBloomBean stockBloomBean) {
        if (stockBloomBean != null) {
            switch (stockBloomBean.getStatus()) {
                case 1:
                    isFall = false;
                    if (fallingView != null) {
                        fallingView.setVisibility(View.GONE);
                    }
                    if (iv_boom_handred.getVisibility() == View.VISIBLE) {
                        iv_boom_handred.setVisibility(View.GONE);
//                        if (handredAnima != null) {
//                            handredAnima.stop();
//                        }
                    }
                    if (isSubscribe) {
                        if (TextUtils.isEmpty(subscribeBetMoney) || TextUtils.isEmpty(subscribeBetValue)) {
                            return;
                        }
                        if (!isSubscriCommit) {
                            mPresenter.normalBet("cny", subscribeBetMoney, subscribeBetValue);
//                            switch (subscribeBetType) {
//                                case 0://JC
//                                    mPresenter.normalBet("pb", subscribeBetMoney, subscribeBetValue);
//                                    break;
//                                case 1://USDT
//                                    mPresenter.normalBet("cny", subscribeBetMoney, subscribeBetValue);
//                                    break;
//                            }
                            isSubscriCommit = true;
                        }
                    }
                    tvAwardPoll.setText("奖池 " + stockBloomBean.getData().get(0).getPrepare().getStart_cny_pool_money() + " USDT");
//                    switch (money_type) {
//                        case 0:
//                            tvAwardPoll.setText("奖池 " + stockBloomBean.getData().get(0).getPrepare().getStart_pb_pool_money() + " JC");
//                            break;
//                        case 1:
//                            tvAwardPoll.setText("奖池 " + stockBloomBean.getData().get(0).getPrepare().getStart_cny_pool_money() + " USDT");
//                            break;
//                    }
                    if (userData != null) {
                        mPresenter.getUsersInfo();
                    }
                    mPresenter.getOpenAwardList(userData == null ? "" : userData.getAccount());
                    boomView.gamePreparing((int) (Double.valueOf(stockBloomBean.getData().get(0).getPrepare().getSt())
                            - Double.valueOf(stockBloomBean.getData().get(0).getPrepare().getPt())));
                    break;
                case 2:
                    boomView.gameStart();
                    isSubscriCommit = false;
                    escapeBeans = new ArrayList<>();
                    if (userData != null) {
                        if (stockBloomBean.getData().get(2).getEscape_list().size() > 0) {
                            for (int i = 0; i < stockBloomBean.getData().get(2).getEscape_list().size(); i++) {
                                if (stockBloomBean.getData().get(2).getEscape_list().get(i).getUid().equals(userid)) {
                                    escapeBeans.add(new EscapeBean(
                                            stockBloomBean.getData().get(2).getEscape_list().get(i).getRealname()
                                            , Float.parseFloat(stockBloomBean.getData().get(2).getEscape_list().get(i).getFinal_beishu())));
                                }
                            }
                            boomView.setEscapeBeans(escapeBeans);
                        }
                    }
                    tvAwardPoll.setText("奖池 " + stockBloomBean.getData().get(0).getProcess().getStart_cny_pool_money() + " USDT");
//                    switch (money_type) {
//                        case 0:
//                            tvAwardPoll.setText("奖池 " + stockBloomBean.getData().get(0).getProcess().getStart_pb_pool_money() + " JC");
//                            break;
//                        case 1:
//                            tvAwardPoll.setText("奖池 " + stockBloomBean.getData().get(0).getProcess().getStart_cny_pool_money() + " USDT");
//                            break;
//                    }
                    break;
                case 3:
                    if (!isFall) {
                        if (fallObject != null && fallingView != null) {
                            fallingView.setVisibility(View.VISIBLE);
                            fallingView.addFallObject(fallObject, 30);//添加50个下落物体对象
                            isFall = true;
                        }
                    }
                    tvAwardPoll.setText("奖池 " + stockBloomBean.getData().get(0).getCrash().getStart_cny_pool_money() + " USDT");
//                    switch (money_type) {
//                        case 0:
//                            tvAwardPoll.setText("奖池 " + stockBloomBean.getData().get(0).getCrash().getStart_pb_pool_money() + " JC");
//                            break;
//                        case 1:
//                            tvAwardPoll.setText("奖池 " + stockBloomBean.getData().get(0).getCrash().getStart_cny_pool_money() + " USDT");
//                            break;
//                    }
                    boomView.gameOver((float) stockBloomBean.getData().get(0).getCrash().getBoomValue());
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void connectSocket(SocketBean socketBean) {
//        if (socketBean != null) {
//            switch (socketBean.getState()) {
//                case 0:
//                    if (boomView != null && !boomView.isCanDraw()) {
//                        boomView.setCanDraw(true);
//                    }
//                    break;
//                case 1:
//                    ToastUtil.showShort("网络异常");
//                    if (boomView != null) {
//                        boomView.setCanDraw(false);
//                    }
//                    break;
//            }
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void logout(LogoutBean socketBean) {
        mainMenuBeans.clear();
        if (spinnerAdapter != null) {
            spinnerAdapter.notifyDataSetChanged();
        }
        tvMoney.setText("0.0000USDT");
        iv_money_type.setImageDrawable(App.INSTANCE.getResources().getDrawable(R.mipmap.app_icon_usdt));
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (userData != null) {
            mPresenter.getUsersInfo();
        }
        if (ll_wanfa_anim.getVisibility() == View.GONE) {
//            ll_wanfa_anim.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (ll_wanfa_anim.getVisibility() == View.GONE) {
//                ll_wanfa_anim.setVisibility(View.VISIBLE);
            }
            if (fallObject == null) {
                //初始化一个金币样式的fallObject
                FallObject.Builder builder = new FallObject.Builder(getResources().getDrawable(R.mipmap.app_icon_gold));
                fallObject = builder
                        .setSpeed(40, true)
                        .setSize(80, 80, false)
                        .setWind(5, true, true)
                        .build();
            }
        } else {
            fallObject = null;
            if (isSubscribe) {
                isSubscribe = false;
                subscribeBetMoney = "";
                subscribeBetValue = "";
            }
        }
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.getUsersInfo();
            } else {
                userData = null;
            }
            mPresenter.getOpenAwardList(userData == null ? "" : userData.getAccount());
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (fallObject == null) {
            //初始化一个金币样式的fallObject
            FallObject.Builder builder = new FallObject.Builder(getResources().getDrawable(R.mipmap.app_icon_gold));
            fallObject = builder
                    .setSpeed(40, true)
                    .setSize(80, 80, false)
                    .setWind(5, true, true)
                    .build();
        }
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        if (boomView != null) {
            boomView.setDrawing(true);
        }
//        }
    }

    @Override
    public void onPause() {
        super.onPause();
        fallObject = null;
        if (isSubscribe) {
            isSubscribe = false;
            subscribeBetMoney = "";
            subscribeBetValue = "";
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
            if (boomView != null) {
                boomView.setDrawing(false);
            }
        }
//        if (boomView != null) {
//            boomView.setDrawing(false);
//        }
    }

    @SuppressLint("CheckResult")
    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        RxBus.getDefault().register(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.getUsersInfo();
            } else {
                userData = null;
            }
        });
        mPresenter.getOpenAwardList(userData == null ? "" : userData.getAccount());
        mPresenter.getCommonData();

        ImageUtil.setOriginImage(R.mipmap.hundred, iv_boom_handred);

        if (fallObject == null) {
            //初始化一个金币样式的fallObject
            FallObject.Builder builder = new FallObject.Builder(getResources().getDrawable(R.mipmap.app_icon_gold));
            fallObject = builder
                    .setSpeed(40, true)
                    .setSize(80, 80, false)
                    .setWind(5, true, true)
                    .build();
        }

        initTab();
//        initBoomAnim();
//        initOneHandredAnim();
//
        initSpinner();
        initBoomView();
        initRecyHistory();
        initSlideTabLayout();

        boomView.setBoomListener(new BoomView.BoomListener() {
            @Override
            public void boom() {
                getActivity().runOnUiThread(() -> {
                    isBet = false;
                    isRun = false;
                    isBoom = true;
                    if (tv_now_value == null) {
                        return;
                    }
                    tv_now_value.setVisibility(View.INVISIBLE);
                    tv_show_run.setVisibility(View.INVISIBLE);
                    tv_now_value.setText("");
                    tv_show_run.setText("");
                    if (userData == null) {
                        if (btnBet != null) {
                            btnBet.setClickable(true);
                        }
                        btnBet.setText(App.INSTANCE.getString(R.string.app_boom));
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_10a));
                        return;
                    }
                    if (btnBet != null) {
                        btnBet.setClickable(false);
                    }
                    if (isSubscribe) {
                        btnBet.setText(App.INSTANCE.getString(R.string.app_wait));
                    } else {
                        btnBet.setText(App.INSTANCE.getString(R.string.app_boom));

                    }
                    btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_10a));
                });
            }

            @Override
            public void prePare() {
                getActivity().runOnUiThread(() -> {
                    isRun = false;
                    isBoom = false;
                    if (tv_now_value == null) {
                        return;
                    }
                    tv_now_value.setVisibility(View.INVISIBLE);
                    tv_show_run.setVisibility(View.INVISIBLE);
                    tv_now_value.setText("");
                    tv_show_run.setText("");
                    if (userData == null) {
                        if (btnBet != null) {
                            btnBet.setClickable(true);
                        }
                        btnBet.setText(App.INSTANCE.getString(R.string.app_bet));
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_10a));
                        return;
                    }
                    if (isBet) {
                        btnBet.setText(App.INSTANCE.getString(R.string.app_wait));
                        if (btnBet != null) {
                            btnBet.setClickable(false);
                        }
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_10a));
                    } else {
                        btnBet.setText(App.INSTANCE.getString(R.string.app_bet));
                        if (btnBet != null) {
                            btnBet.setClickable(true);
                        }
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_bg));
                    }
                });
            }

            @Override
            public void onTextChange(String nowTime) {
                getActivity().runOnUiThread(() -> {
                    if (tv_now_value == null) {
                        return;
                    }
                    if (btnBet != null) {
                        btnBet.setClickable(true);
                    }
                    if (Float.parseFloat(nowTime) > 100) {
                        iv_boom_handred.setVisibility(View.VISIBLE);
                        if (iv_boom_handred.getVisibility() == View.GONE) {
                            iv_boom_handred.setVisibility(View.VISIBLE);
//                            if (handredAnima != null) {
//                                handredAnima.stop();
//                                handredAnima.start();
//                            }
                        }
                    }
                    tv_now_value.setVisibility(View.VISIBLE);
                    tv_show_run.setVisibility(View.VISIBLE);
                    btnBet.setText("");
                    if (userData == null) {
                        tv_now_value.setText(App.INSTANCE.getString(R.string.app_subscribe));
                        tv_show_run.setText(App.INSTANCE.getString(R.string.app_next_game));
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_10a));
                        return;
                    }
                    if (!isBet) {
                        if (!isSubscribe) {
                            tv_now_value.setText(App.INSTANCE.getString(R.string.app_subscribe));
                            tv_show_run.setText(App.INSTANCE.getString(R.string.app_next_game));
                        } else {
                            tv_now_value.setText(App.INSTANCE.getString(R.string.app_wait));
                            tv_show_run.setText(App.INSTANCE.getString(R.string.app_cancle));
                        }
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_bg));
                        return;
                    }
                    if (isRun) {
                        if (!isSubscribe) {
                            tv_now_value.setText(App.INSTANCE.getString(R.string.app_subscribe));
                            tv_show_run.setText(App.INSTANCE.getString(R.string.app_next_game));
                        } else {
                            tv_now_value.setText(App.INSTANCE.getString(R.string.app_wait));
                            tv_show_run.setText(App.INSTANCE.getString(R.string.app_cancle));
                        }
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_bg));
                        return;
                    }
                    BigDecimal bet = new BigDecimal(betMoney);
                    BigDecimal time = new BigDecimal(nowTime);
                    tv_now_value.setText(bet.multiply(time) + " " + betType);
                    tv_show_run.setText(App.INSTANCE.getString(R.string.app_run_small));
                    btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_bg));
                    if (Float.parseFloat(nowTime) > betValue) {
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_bg));
                        tv_now_value.setText(App.INSTANCE.getString(R.string.app_subscribe));
                        tv_show_run.setText(App.INSTANCE.getString(R.string.app_next_game));
                        isRun = true;
                        return;
                    }
                });
            }
        });

        //用户协议
        ClickUtil.click(tvUserAgreement, () -> RxBus.getDefault().post(new MainChangeTabBean(0)));
        //隐私协议
        ClickUtil.click(tvPrivacyAgreement, () -> RxBus.getDefault().post(new MainChangeTabBean(1)));
        //帮助中心
        ClickUtil.click(tvHelpCenter, () -> RxBus.getDefault().post(new MainChangeTabBean(2)));
        //APP下载
        ClickUtil.click(tvAppDownload, () -> RxBus.getDefault().post(new MainChangeTabBean(3)));

        ClickUtil.click(rlAssetRecord, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            ARouter.getInstance().build(RConfig.APP_ASSET).navigation();
        });
        ClickUtil.click(rlBankerJackpot, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
//            ARouter.getInstance().build(RConfig.APP_BANKER_JACKPOT).withString(Constans.MONEY_TYPE, money_type == 0 ? "JC" : "USDT").navigation();
            ARouter.getInstance().build(RConfig.APP_BANKER_JACKPOT).withString(Constans.MONEY_TYPE, "USDT").navigation();
        });
        //关闭玩法介绍动画
        ClickUtil.click(tv_clear_wanfa, () -> {
            ll_wanfa_anim.setVisibility(View.GONE);
        });
        //玩法介绍点击跳转
        ClickUtil.click(ivBg, () -> ARouter.getInstance().build(RConfig.APP_PLAY_INTEODUCE).navigation());

        tvEarn.setText("收益 0.00");

        RxTextView.textChanges(etBet)
                .debounce(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map(CharSequence::toString)
                .subscribe(s -> {
                    if (TextUtils.isEmpty(s)) {
                        s = "0";
                    }
                    if (s.startsWith("0") && s.length() > 1) {
                        etBet.setText(s.substring(1, s.length()));
                    }
                    if (!TextUtils.isEmpty(s) && !TextUtils.isEmpty(usdtBetMax)) {
                        if (Float.parseFloat(s) > Float.valueOf(usdtBetMax)) {
                            etBet.setText(usdtBetMax);
                        }
                    }
//                    switch (money_type) {
//                        case 0:
//                            if (!TextUtils.isEmpty(s) && !TextUtils.isEmpty(betMax)) {
//                                if (Float.parseFloat(s) > Float.valueOf(betMax)) {
//                                    etBet.setText(betMax);
//                                }
//                            }
//                            break;
//                        case 1:
//                            if (!TextUtils.isEmpty(s) && !TextUtils.isEmpty(usdtBetMax)) {
//                                if (Float.parseFloat(s) > Float.valueOf(usdtBetMax)) {
//                                    etBet.setText(usdtBetMax);
//                                }
//                            }
//                            break;
//                    }
                    if (s.contains(".")) {
                        etBet.setText(NumberUtil.keepDown(s, 0, false));
                        tvEarn.setText("收益" + NumberUtil.keep2(Float.parseFloat(etBet.getText().toString()) * Float.parseFloat(
                                TextUtils.isEmpty(etRunAway.getText().toString()) ? "0" : etRunAway.getText().toString().trim())));
                        return;
                    }
                    tvEarn.setText("收益" + NumberUtil.keep2(Float.parseFloat(s) * Float.parseFloat(
                            TextUtils.isEmpty(etRunAway.getText().toString()) ? "0" : etRunAway.getText().toString().trim())));
                });


        RxTextView.textChanges(etRunAway)
                .debounce(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map(CharSequence::toString)
                .subscribe(s -> {
                    if (s.startsWith(".")) {
                        ToastUtil.showShort("请输入正确的倍数");
                        return;
                    }
                    if (TextUtils.isEmpty(s)) {
                        s = "1.1";
                    }
                    if (Float.parseFloat(s) < 1.1) {
                        ToastUtil.showShort("逃跑倍数不能低于1.1");
                        s = "1.1";
                    }
                    if (NumberUtil.isLittleNumber(s) && NumberUtil.isTwoLittleNumber(s)) {
                        etRunAway.setText(NumberUtil.keepDown(s, 1, false));
                        tvEarn.setText("收益" + NumberUtil.keep2(Float.parseFloat(etRunAway.getText().toString()) * Float.parseFloat(TextUtils.isEmpty(etBet.getText().toString()) ? "0" : etBet.getText().toString().trim())));
                        return;
                    }
                    tvEarn.setText("收益" + NumberUtil.keep2(Float.parseFloat(s) * Float.parseFloat(TextUtils.isEmpty(etBet.getText().toString()) ? "0" : etBet.getText().toString().trim())));
                    tvChance.setText("机会 " + NumberUtil.keep2(100 / Float.parseFloat(s.trim())) + "%");
                });
//        RxAdapterView.itemSelections(spinner)
//                .subscribe(pos -> {
//                    if (money_type != pos) {
//                        money_type = pos;
//                        switch (money_type) {
//                            case 0:
//                                etBet.setText(betMin);
//                                etRunAway.setText(betBeishu);
//                                break;
//                            case 1:
//                                etBet.setText(usdtBetMin);
//                                etRunAway.setText(usdtBetBeishu);
//                                break;
//                        }
//                    }
//                    if (mainMenuBeans == null || mainMenuBeans.size() < 2) {
//                        return;
//                    }
//                    switch (pos) {
//                        case 0:
//                            etBet.setHint("投注范围 " + betMin + "-" + betMax);
//                            tvMoney.setText(mainMenuBeans.get(pos).getContent());
//                            iv_money_type.setImageDrawable(App.INSTANCE.getResources().getDrawable(R.mipmap.app_icon_qc));
//                            break;
//                        case 1:
//                            etBet.setHint("投注范围 " + usdtBetMin + "-" + usdtBetMax);
//                            tvMoney.setText(mainMenuBeans.get(pos).getContent());
//                            iv_money_type.setImageDrawable(App.INSTANCE.getResources().getDrawable(R.mipmap.app_icon_usdt));
//                            break;
//                        default:
//                            break;
//                    }
//                });

        ClickUtil.click(tvMax, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            if (TextUtils.isEmpty(betMax) || TextUtils.isEmpty(betMin) || TextUtils.isEmpty(usdtBetMax) || TextUtils.isEmpty(usdtBetMin)) {
                ToastUtil.showShort("数据获取失败");
                mPresenter.getCommonData();
                return;
            }
            etBet.setText(usdtBetMax);
//            switch (money_type) {
//                case 0:
//                    etBet.setText(betMax);
//                    break;
//                case 1:
//                    etBet.setText(usdtBetMax);
//                    break;
//            }
        });
        ClickUtil.click(tvMin, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            if (TextUtils.isEmpty(betMax) || TextUtils.isEmpty(betMin) || TextUtils.isEmpty(usdtBetMax) || TextUtils.isEmpty(usdtBetMin)) {
                ToastUtil.showShort("数据获取失败");
                mPresenter.getCommonData();
                return;
            }
            etBet.setText(usdtBetMin);
//            switch (money_type) {
//                case 0:
//                    etBet.setText(betMin);
//                    break;
//                case 1:
//                    etBet.setText(usdtBetMin);
//                    break;
//            }
        });
        ClickUtil.click(300, tvDivide, () -> {
            if (userData == null) {
                toLogin();
                return;
            }

            if (TextUtils.isEmpty(betMax)
                    || TextUtils.isEmpty(betMin)
                    || TextUtils.isEmpty(usdtBetMax)
                    || TextUtils.isEmpty(usdtBetMin)) {
                ToastUtil.showShort("获取信息失败");
                mPresenter.getCommonData();
                return;
            }
            if (TextUtils.isEmpty(etBet.getText().toString())) {
                return;
            }
            if (Float.parseFloat(etBet.getText().toString().trim()) / 2 < Float.parseFloat(usdtBetMin)) {
                ToastUtil.showShort("投注数目不能低于" + Float.parseFloat(usdtBetMin));
                etBet.setText(usdtBetMin);
                return;
            }
            etBet.setText(Float.parseFloat(etBet.getText().toString().trim()) / 2 + "");
//            switch (money_type) {
//                case 0://JC
//                    if (Float.parseFloat(etBet.getText().toString().trim()) / 2 < Float.parseFloat(betMin)) {
//                        ToastUtil.showShort("投注数目不能低于" + Float.parseFloat(betMin));
//                        etBet.setText(betMin);
//                        return;
//                    }
//                    etBet.setText(Float.parseFloat(etBet.getText().toString().trim()) / 2 + "");
//                    break;
//                case 1://USDT
//                    if (Float.parseFloat(etBet.getText().toString().trim()) / 2 < Float.parseFloat(usdtBetMin)) {
//                        ToastUtil.showShort("投注数目不能低于" + Float.parseFloat(usdtBetMin));
//                        etBet.setText(usdtBetMin);
//                        return;
//                    }
//                    etBet.setText(Float.parseFloat(etBet.getText().toString().trim()) / 2 + "");
//                    break;
//            }
        });
        ClickUtil.click(300, tvMultiply, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            if (TextUtils.isEmpty(betMax)
                    || TextUtils.isEmpty(betMin)
                    || TextUtils.isEmpty(usdtBetMax)
                    || TextUtils.isEmpty(usdtBetMin)) {
                ToastUtil.showShort("获取信息失败");
                mPresenter.getCommonData();
                return;
            }
            if (TextUtils.isEmpty(etBet.getText().toString())) {
                return;
            }
            if (Float.parseFloat(etBet.getText().toString().trim()) * 2 > Float.parseFloat(usdtBetMax)) {
                ToastUtil.showShort("投注数目不能高于" + Float.parseFloat(usdtBetMax));
                etBet.setText(usdtBetMax);
                return;
            }
            etBet.setText(Float.parseFloat(etBet.getText().toString().trim()) * 2 + "");
//            switch (money_type) {
//                case 0://JC
//                    if (Float.parseFloat(etBet.getText().toString().trim()) * 2 > Float.parseFloat(betMax)) {
//                        ToastUtil.showShort("投注数目不能高于" + Float.parseFloat(betMax));
//                        etBet.setText(betMax);
//                        return;
//                    }
//                    etBet.setText(Float.parseFloat(etBet.getText().toString().trim()) * 2 + "");
//                    break;
//                case 1://USDT
//                    if (Float.parseFloat(etBet.getText().toString().trim()) * 2 > Float.parseFloat(usdtBetMax)) {
//                        ToastUtil.showShort("投注数目不能高于" + Float.parseFloat(usdtBetMax));
//                        etBet.setText(usdtBetMax);
//                        return;
//                    }
//                    etBet.setText(Float.parseFloat(etBet.getText().toString().trim()) * 2 + "");
//                    break;
//            }
        });

        ClickUtil.click(btnBet, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            if (TextUtils.isEmpty(betMax)
                    || TextUtils.isEmpty(betMin)
                    || TextUtils.isEmpty(usdtBetMax)
                    || TextUtils.isEmpty(usdtBetMin)) {
                ToastUtil.showShort("获取信息失败");
                mPresenter.getCommonData();
                return;
            }
            //准备阶段
            if (btnBet.getText().equals("投注")) {

                if (checkBet()) {
                    mPresenter.normalBet("cny", etBet.getText().toString().trim(), etRunAway.getText().toString().trim());
//                    switch (money_type) {
//                        case 0://JC
//                            mPresenter.normalBet("pb", etBet.getText().toString().trim(), etRunAway.getText().toString().trim());
//                            break;
//                        case 1://USDT
//                            mPresenter.normalBet("cny", etBet.getText().toString().trim(), etRunAway.getText().toString().trim());
//                            break;
//                    }
                }
                return;
            }
            //游戏阶段
            if (isBet) {
                if (isRun) {
                    if (isSubscribe) {
                        isSubscribe = false;
                        subscribeBetMoney = "";
                        subscribeBetValue = "";
                    } else {
                        if (checkBet()) {
                            isSubscribe = true;
                            subscribeBetMoney = etBet.getText().toString().trim();
                            subscribeBetValue = etRunAway.getText().toString();
                        }
                    }
                } else {
                    mPresenter.normalRun();
                }
            } else {
                if (isSubscribe) {
                    isSubscribe = false;
                    subscribeBetMoney = "";
                    subscribeBetValue = "";
                } else {
                    if (checkBet()) {
                        isSubscribe = true;
                        subscribeBetMoney = etBet.getText().toString().trim();
                        subscribeBetValue = etRunAway.getText().toString();
//                        subscribeBetType = money_type;
                    }
                }
            }

        });
    }

    private boolean checkBet() {
        if (TextUtils.isEmpty(etBet.getText().toString())) {
            ToastUtil.showShort("请输入投注数目");
            return false;
        }
        if (TextUtils.isEmpty(etRunAway.getText().toString())) {
            ToastUtil.showShort("请输入逃跑倍数");
            return false;
        }
        if (Float.parseFloat(etRunAway.getText().toString().trim()) < 1.1) {
            ToastUtil.showShort("逃跑倍数不能低于1.1");
            return false;
        }
        return true;
    }

    private void initSpinner() {
        spinnerAdapter = new QiangjinSpinnerAdapter(mainMenuBeans, getActivity());
        spinner.setAdapter(spinnerAdapter);
        spinner.setSelection(0);
//        spinner.setDropDownVerticalOffset(140);
    }

    private void initSlideTabLayout() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        ArrayList<String> titles = new ArrayList<>();
        titles.add("我的竞猜");
        titles.add("我的订单");
        titles.add("开奖历史");
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_ALL_GUESS).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_MY_GUESS_HISTORY).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_OPEN_AWARD_HISTORY).navigation());
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), titles, fragments));
        slidingTabLayout.setViewPager(viewPager);
    }

    private void initRecyHistory() {
        ArrayList<String> strings = new ArrayList<>();
        strings.add("1");
        strings.add("2");
        strings.add("3");
        strings.add("4");
        strings.add("5");
        recyclerViewHistory.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        recyclerViewHistory.addItemDecoration(new DividerHorizenLineItemDecoration(getActivity())
                .setFirstDraw(false)
                .setLastDraw(false)
                .setTopPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 13))
                .setBottomPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 13))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 0.6f))
                .setPaintColor(ContextCompat.getColor(App.INSTANCE, R.color.app_f2f))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_main_history, new SlimInjector<OpenAwardBean>() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onInject(OpenAwardBean data, IViewInjector injector, List payloads) {
                if (slimAdapter.getData().indexOf(data) == 0 || slimAdapter.getData().indexOf(data) == 2) {
                    injector.textColor(R.id.tvScale, ContextCompat.getColor(getActivity(), R.color.app_80e));
                }
                if (slimAdapter.getData().indexOf(data) == 1) {
                    injector.textColor(R.id.tvScale, ContextCompat.getColor(getActivity(), R.color.app_e8f));
                }
                if (slimAdapter.getData().indexOf(data) == 3) {
                    injector.textColor(R.id.tvScale, ContextCompat.getColor(getActivity(), R.color.app_e64));
                }
                if (slimAdapter.getData().indexOf(data) == 4) {
                    injector.textColor(R.id.tvScale, ContextCompat.getColor(getActivity(), R.color.app_e9b));
                }
                injector.text(R.id.tv_id, data.getPeriodID())
                        .text(R.id.tvScale, data.getBoomValue() + "X");
            }
        }).attachTo(recyclerViewHistory).updateData(new ArrayList());

    }

    private void initBoomView() {
        boomView.setLineTextColor(ContextCompat.getColor(App.INSTANCE, R.color.app_e4e));
        boomView.setStrokeColor(ContextCompat.getColor(App.INSTANCE, R.color.app_e4e));
        boomView.setShowTextColor(ContextCompat.getColor(App.INSTANCE, R.color.app_da7));
        boomView.setBgColor(ContextCompat.getColor(App.INSTANCE, R.color.app_solid));
    }

    private void initTab() {
        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem("竞猜", R.mipmap.app_icon_my_guess, R.mipmap.app_icon_my_guess));
        tabItems.add(new TabItem("FAQ", R.mipmap.app_icon_question, R.mipmap.app_icon_question));
//        tabItems.add(new TabItem("排行榜", R.mipmap.app_icon_tab_rank, R.mipmap.app_icon_tab_rank));
        tabItems.add(new TabItem("APP", R.mipmap.app_icon_menu_download, R.mipmap.app_icon_menu_download));
        tabItems.add(new TabItem("公平", R.mipmap.app_icon_tab_fair, R.mipmap.app_icon_tab_fair));
        commonTabLayout.setTabData(tabItems);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switch (position) {
                    case 0:
                        break;
                    case 1:
                        ARouter.getInstance().build(RConfig.APP_FAQ).navigation();
                        break;
//                    case 2:
//                        ARouter.getInstance().build(RConfig.APP_RANK).navigation();
//                        break;
                    case 2:
                        RxBus.getDefault().post(new MainChangeTabBean(3));
                        break;
                    case 3:
                        ARouter.getInstance().build(RConfig.APP_FAQ).withString(Constans.POSITION, "2").navigation();
                        break;
                    default:
                        break;
                }
                commonTabLayout.setCurrentTab(0);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    public void updataUI(CommonBean commonBean) {
        betMin = commonBean.getBuy_info().getPb_info().getPb_buy_min_money();
        betMax = commonBean.getBuy_info().getPb_info().getPb_buy_max_money();
        betBeishu = commonBean.getBuy_info().getPb_info().getPb_escape_beishu();
        usdtBetMax = commonBean.getBuy_info().getCny_info().getCny_buy_max_money();
        usdtBetMin = commonBean.getBuy_info().getCny_info().getCny_buy_min_money();
        usdtBetBeishu = commonBean.getBuy_info().getCny_info().getCny_escape_beishu();

        etBet.setHint("投注范围 " + usdtBetMin + "-" + usdtBetMax);
        etBet.setText(usdtBetMin);
        etRunAway.setText(usdtBetBeishu);
//        switch (money_type) {
//            case 0:
//                etBet.setHint("投注范围 " + betMin + "-" + betMax);
//                etBet.setText(betMin);
//                etRunAway.setText(betBeishu);
//                break;
//            case 1:
//                etBet.setHint("投注范围 " + usdtBetMin + "-" + usdtBetMax);
//                etBet.setText(usdtBetMin);
//                etRunAway.setText(usdtBetBeishu);
//                break;
//        }
    }

    public void updataAwardHistory(List<OpenAwardBean> datas) {
        int size = datas.size();
        if (size < 6 && size > 0) {
            slimAdapter.updateData(datas.subList(0, size));
        } else if (size > 5) {
            slimAdapter.updateData(datas.subList(0, 5));
        }
    }

    public void updateUser(UserBean userBean) {
        if (userBean != null) {
            tvMoney.setText(NumberUtil.keep4(userBean.getBalance_cny()) + " USDT（1USDT=$1）");
            iv_money_type.setImageDrawable(App.INSTANCE.getResources().getDrawable(R.mipmap.app_icon_usdt));
//            switch (money_type) {
//                case 0:
//                    tvMoney.setText(NumberUtil.keep4(userBean.getBalance_pb()) + " JC");
//                    iv_money_type.setImageDrawable(App.INSTANCE.getResources().getDrawable(R.mipmap.app_icon_qc));
//                    break;
//                case 1:
//                    tvMoney.setText(NumberUtil.keep4(userBean.getBalance_cny()) + " USDT（1USDT=$1）");
//                    iv_money_type.setImageDrawable(App.INSTANCE.getResources().getDrawable(R.mipmap.app_icon_usdt));
//                    break;
//            }
            userid = userBean.getUserid();
        }
        mainMenuBeans.clear();
        mainMenuBeans.add(new MainMenuBean(R.mipmap.app_icon_qc, NumberUtil.keep4(userBean.getBalance_pb()) + " JC"));
        mainMenuBeans.add(new MainMenuBean(R.mipmap.app_icon_usdt, NumberUtil.keep4(userBean.getBalance_cny()) + " USDT（1USDT=$1）"));
        spinnerAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    private void toLogin() {
        if (loginTip == null) {
            loginTip = TipMineUtil.getTip(getActivity(), "请先登录", "去登录", () -> {
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
            });
        }
        loginTip.show();
    }

    /**
     * 下注成功
     * 按钮背景颜色变为红色
     */
    public void betSuccess(String type, String money, String escape_beishu) {
        this.isSubscribe = false;
        this.betType = type.equals("pb") ? "JC" : "USDT";
        this.betMoney = Double.parseDouble(money);
        this.betValue = Float.parseFloat(escape_beishu);
        isRun = false;
        isBet = true;
    }

    /**
     * 下注成功
     * 按钮背景颜色变为红色
     */
    public void betFail() {
        this.isSubscribe = false;
        isRun = false;
    }

    /**
     * 逃跑成功
     * 按钮文字变为 逃跑
     * 不可点击
     * 背景颜色变为绿色
     */
    public void runSuccess() {
        isRun = true;
        isBet = false;
    }

    private void initOneHandredAnim() {
        handredAnima = new AnimationDrawable();
        Drawable drawable0 = getResources().getDrawable(R.mipmap.c1);
        Drawable drawable1 = getResources().getDrawable(R.mipmap.c2);
        Drawable drawable2 = getResources().getDrawable(R.mipmap.c3);
        Drawable drawable3 = getResources().getDrawable(R.mipmap.c4);
        Drawable drawable4 = getResources().getDrawable(R.mipmap.c5);
        Drawable drawable5 = getResources().getDrawable(R.mipmap.c6);
        Drawable drawable6 = getResources().getDrawable(R.mipmap.c7);
        Drawable drawable7 = getResources().getDrawable(R.mipmap.c8);
        handredAnima.addFrame(drawable0, 100);
        handredAnima.addFrame(drawable1, 100);
        handredAnima.addFrame(drawable2, 100);
        handredAnima.addFrame(drawable3, 100);
        handredAnima.addFrame(drawable4, 100);
        handredAnima.addFrame(drawable5, 100);
        handredAnima.addFrame(drawable6, 100);
        handredAnima.addFrame(drawable7, 100);
        handredAnima.setOneShot(false);
        iv_boom_handred.setImageDrawable(handredAnima);
        // 获取资源对象
        handredAnima.stop();
        // 特别注意：在动画start()之前要先stop()，不然在第一次动画之后会停在最后一帧，这样动画就只会触发一次
        handredAnima.start();
    }

//    private void initBoomAnim() {
//        boomAnimationDrawable = new AnimationDrawable();
//        Drawable drawable0 = getResources().getDrawable(R.mipmap.b2);
//        Drawable drawable1 = getResources().getDrawable(R.mipmap.b3);
//        Drawable drawable2 = getResources().getDrawable(R.mipmap.b4);
//        Drawable drawable3 = getResources().getDrawable(R.mipmap.b5);
//        Drawable drawable4 = getResources().getDrawable(R.mipmap.b6);
//        Drawable drawable5 = getResources().getDrawable(R.mipmap.b7);
//        Drawable drawable6 = getResources().getDrawable(R.mipmap.b1);
//        boomAnimationDrawable.addFrame(drawable0, 150);
//        boomAnimationDrawable.addFrame(drawable1, 150);
//        boomAnimationDrawable.addFrame(drawable2, 150);
//        boomAnimationDrawable.addFrame(drawable3, 150);
//        boomAnimationDrawable.addFrame(drawable4, 150);
//        boomAnimationDrawable.addFrame(drawable5, 150);
//        boomAnimationDrawable.addFrame(drawable6, 150);
//        boomAnimationDrawable.setOneShot(true);
//        iv_boom.setImageDrawable(boomAnimationDrawable);
//        boomAnimationDrawable.stop();
//    }
}
